<template>
    <div class="flex order-list-container">
        <!-- 客户列表 -->
        <div v-show="!customerInfo.customerId" class="mr-1">
            <CustomerList v-model="customerInfo" width="300px" height="calc(100vh - 120px)" customerAbbreviation></CustomerList>
        </div>

        <!-- 客户订单信息展示 -->
        <div v-if="!customerInfo.customerId" class="w-full flex flex-wrap justify-center">
            <!-- 未处理数据列表 -- 当没有客户id时显示 -->
            <el-tabs v-model="activeName" class="w-full" @tab-click="handleTabClick">
                <!-- 未处理订单 -->
                <el-tab-pane label="未处理订单" name="unprocessedOrder">
                    <div
                        v-if="unprocessedOrder.length == 0 && loading"
                        v-loading="loading"
                        element-loading-text="加载中所有未处理订单，请稍后..."
                        class="w-full mt-5"
                    />
                    <el-empty v-if="unprocessedOrder.length == 0 && !loading" description="没有未处理的订单" />
                    <div v-if="unprocessedOrder.length !== 0" class="w-full p-4">
                        <el-descriptions title="未处理订单数据列表（仅展示10条）" :column="4" border>
                            <template #extra>
                                <el-text tag="b" type="primary">
                                    服务器当前还有
                                    <el-text tag="b" type="warning">
                                        {{ unprocessedOrderTotal }}
                                    </el-text>
                                    条数据未处理
                                </el-text>
                            </template>
                            <div v-for="(item, index) in unprocessedOrder" :key="index">
                                <el-descriptions-item>
                                    <template #label>订单日期</template>
                                    {{ formatTimeZone(item.orderDate, 'YYYY-MM-DD') }}
                                </el-descriptions-item>
                                <el-descriptions-item>
                                    <template #label>客户名称</template>
                                    {{ matchCustomerName(item.customerId) }}
                                </el-descriptions-item>
                                <el-descriptions-item>
                                    <template #label>订单号</template>
                                    {{ item.orderNo }}
                                </el-descriptions-item>
                                <el-descriptions-item>
                                    <template #label>送货日期</template>
                                    {{
                                        item.orderDeliveryDate == '暂无送货计划'
                                            ? item.orderDeliveryDate
                                            : formatTimeZone(item.orderDeliveryDate, 'YYYY-MM-DD')
                                    }}
                                </el-descriptions-item>
                            </div>
                        </el-descriptions>
                    </div>
                </el-tab-pane>

                <!-- 所有未发货订单 -->
                <el-tab-pane label="未发货订单" name="unprocessedOrderDelivery">
                    <div v-if="unStatusOrder.size >= 0" class="w-full p-4">
                        <el-scrollbar :height="'calc(100vh - 165px)'">
                            <el-descriptions :column="2" border>
                                <template #title> 未发货客户{{ unStatusOrder.size }}个，共{{ unStatusOrderTotal }}个订单 </template>
                                <template #extra>
                                    <el-text tag="b" type="primary">
                                        当前还有
                                        <el-text tag="b" type="warning">
                                            {{ unStatusOrderProductTotal }}
                                        </el-text>
                                        个产品未发货
                                    </el-text>
                                </template>
                                <!-- 循环展示每个客户的未发货订单 -->
                                <div v-for="(item, index) in unStatusOrder" :key="index">
                                    <!-- 展示客户名称 -->
                                    <el-descriptions-item>
                                        <template #label>客户名称</template>
                                        {{ item[0] }}
                                    </el-descriptions-item>

                                    <!-- 取出每个客户的未发货订单号 -->
                                    <el-descriptions-item>
                                        <template #label>未发订单号</template>
                                        {{ item[1].map((order) => order.orderNo).join(', ') }}
                                    </el-descriptions-item>

                                    <!-- 展示每个订单的的未发货产品 -->
                                    <el-descriptions-item :span="2">
                                        <template #label>未发产品</template>
                                        <div v-for="(order, orderIndex) in item[1]" :key="orderIndex">
                                            <div v-for="(detail, productIndex) in order.orderDetail" :key="productIndex">
                                                <div v-if="detail.orderNumber - detail.deliveryQuantity > 0">
                                                    <el-text tag="b" type="primary"> 产品名称：{{ detail.productName }} </el-text>
                                                    &nbsp;&nbsp;&nbsp;&nbsp;
                                                    <el-text tag="b" type="warning"> 订单数量：{{ detail.orderNumber }} </el-text>
                                                    &nbsp;&nbsp;&nbsp;&nbsp;
                                                    <el-text tag="b" type="success"> 已送数量：{{ detail.deliveryQuantity }} </el-text>
                                                    &nbsp;&nbsp;&nbsp;&nbsp;
                                                    <el-text tag="b" type="danger">
                                                        剩余数量：{{ detail.orderNumber - detail.deliveryQuantity }}
                                                    </el-text>
                                                </div>
                                            </div>
                                        </div>
                                    </el-descriptions-item>
                                </div>
                            </el-descriptions>
                        </el-scrollbar>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- 订单列表 -->
        <div v-if="customerInfo.customerId">
            <!-- 列表 -- 当有客户id时显示 -->
            <OrderList
                :customerInfo="customerInfo"
                :width="orderListWidth"
                height="calc(100vh - 80px)"
                options-weight="300px"
                options-height="180px"
                list-height="calc(100vh - 260px)"
                :detail-width="orderDetailWidth"
                detail-height="calc(100vh - 80px)"
            ></OrderList>
        </div>
    </div>
</template>

<script setup lang="ts">
import { getCustomerList } from '@/api/customer';
import { getUnprocessedOrder, getUnStatusOrder } from '@/api/order';
import { useSystemStore } from '@/store/modules/system';
import { formatTimeZone } from '@utils/calculate';
import { TabsPaneContext } from 'element-plus';

// 页面加载时，3S后开始加载未处理订单数据
onMounted(() => {
    updateCustomerListData();
    getUnprocessedOrderEvent();
});

onUnmounted(() => {
    // 取消监听返回客户列表
    instance?.proxy?.$Bus.off('backCustomerList');
});

/* ******************************通用属性/方法****************************** */
// 实时宽度
const useSystem = useSystemStore();
// 计算宽度
const orderListWidth = computed(() => {
    return useSystem.config.isCollapse ? 'calc(100vw - 84px)' : 'calc(100vw - 220px)';
});
// 计算详情宽度
const orderDetailWidth = computed(() => {
    return useSystem.config.isCollapse ? 'calc(100vw - 384px)' : 'calc(100vw - 520px)';
});

// 未处理订单标签页
const activeName = ref('unprocessedOrder');
// 处理tab点击事件
const handleTabClick = async (pane: TabsPaneContext, _ev: Event) => {
    switch (pane.paneName) {
        case 'unprocessedOrder':
            activeName.value = pane.paneName;
            break;
        case 'unprocessedOrderDelivery':
            activeName.value = pane.paneName;
            // 加载数据
            await getUnStatusOrderEvent();
            break;
    }
};

// 组件实例
const instance = getCurrentInstance();
// 客户信息 -- 与子组件CustomerList modelvalue绑定 与子组件OrderList OrderDetail props传递
const customerInfo = reactive({
    customerId: '',
    customerName: '',
    customerAbbreviation: '',
});

// 监听返回客户列表事件，3S后开始加载未处理订单数据
instance?.proxy?.$Bus.on('backCustomerList', function () {
    customerInfo.customerId = '';
    customerInfo.customerName = '';
    customerInfo.customerAbbreviation = '';
    unprocessedOrder.length = 0;
    loading.value = true;

    updateCustomerListData();
    getUnprocessedOrderEvent();
});

/* ******************************加载未处理订单属性/方法****************************** */
// 加载动画
const loading = ref(true);
// 未处理的数据
const unprocessedOrder = reactive<AjaxResponse['orderList']>([]);
// 未处理的数据总数
const unprocessedOrderTotal = ref(0);
// 获取未处理的订单
const getUnprocessedOrderEvent = () => {
    // 清空数据
    unprocessedOrder.length = 0;
    unprocessedOrderTotal.value = 0;
    loading.value = true;
    setTimeout(() => {
        // 请求数据
        getUnprocessedOrder().then((res) => {
            loading.value = false;
            if (res.data.unprocessedOrder.length > 0) {
                // 赋值数据
                unprocessedOrderTotal.value = res.data.unprocessedOrderTotal;
                res.data.unprocessedOrder.forEach((item) => {
                    unprocessedOrder.push(item);
                });
            }
        });
    }, 2000);
};

/* ******************************加载未发货订单属性/方法****************************** */
// 未发货数据
const unStatusOrder = reactive(new Map<string, AjaxResponse['orderList']>());
// 未发货数据总数
const unStatusOrderTotal = ref(0);
// 未发货产品总数
const unStatusOrderProductTotal = ref(0);
// 获取未处理的订单
const getUnStatusOrderEvent = async () => {
    // 清空数据
    unStatusOrder.clear();
    unStatusOrderTotal.value = 0;
    // 请求数据
    const res = await getUnStatusOrder();
    // 赋值数据
    unStatusOrderTotal.value = res.data.unStatusOrderTotal;
    handleStatusOrder(res.data.unStatusOrder);
};
// 处理数据
const handleStatusOrder = (order: AjaxResponse['orderList']) => {
    // 按客户划分
    order.forEach((item) => {
        const customerName = item.customerName;
        if (unStatusOrder.has(customerName)) {
            unStatusOrder.get(customerName)?.push(item);
        } else {
            unStatusOrder.set(customerName, [item]);
        }
    });

    // 计算未发货产品总数
    unStatusOrderProductTotal.value = order.reduce((prev, cur) => {
        return (
            prev +
            cur.orderDetail.reduce((prevDetail, curDetail) => {
                return prevDetail + (curDetail.orderNumber - curDetail.deliveryQuantity);
            }, 0)
        );
    }, 0);
};

// 客户列表数据
type CustomerListItem = {
    customerId: string;
    customerName: string;
    customerAbbreviation: string;
}[];
// 客户列表
const customerList = reactive<CustomerListItem>([]);
// 更新客户列表数据
const updateCustomerListData = () => {
    // 清空表格数据
    customerList.length = 0;
    // 获取客户列表
    getCustomerList(true).then((res) => {
        res.data.forEach((item: any) => {
            const obj = {
                customerId: item._id,
                customerName: item.customerName,
                customerAbbreviation: item.customerAbbreviation,
            };
            customerList.push(obj);
        });
    });
};
// 匹配客户名称
const matchCustomerName = (customerId: string) => {
    return customerList.find((item) => item.customerId === customerId)?.customerName;
};
</script>

<style scoped lang="scss">
.order-list-container {
    height: calc(100vh - 80px);
}
</style>
